package hd.cls7;

import hd.cls6.Student;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author oldliu
 * @since 1.0
 */
public class ClsTest {
    public static void main(String[] args) throws ClassNotFoundException {
        /**
         * 描述类的类。。。
         * 1:获得一个类的描述：类名.class
         * 2：通过对象。。。对象名.getClass()
         * 3:Class.forName("全名");
         */
        Class c = Student.class;
        System.out.println(c.getSuperclass());
        System.out.println(c.getPackage());
        System.out.println(Arrays.toString(c.getInterfaces()));
        Student stu = new Student();
        Class c2 = stu.getClass();
        Class c3 = Class.forName("hd.cls6.Student");
        System.out.println(c == c2);
        System.out.println(c == c3);
        System.out.println(">>>>>>>>>构造方法，普通方法，属性>>>>>>>>>>>");
        Field[] fields = c.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i]);
        }
        System.out.println(">-----------------------");
        Method[] methods = c.getDeclaredMethods();
        for (Method m : methods) {
            System.out.println(m);//方法的签名
        }
        System.out.println(">-------------------");
        Constructor[] cr = c.getDeclaredConstructors();
        for (Constructor c1 : cr) {
            System.out.println(c1);
        }
        System.out.println(">>>>>>>反射调用>>>>>>>>>");
        //内的内省，把一切当成一个字符串，来处理
        try {
            Constructor<Student> c4 = c.getDeclaredConstructor(String.class, int.class);
            c4.setAccessible(true);//突破私有的限制
            Student o = c4.newInstance("老张", 21);

            System.out.println(o);
            Field phone = c.getDeclaredField("phone");
            phone.setAccessible(true);
            phone.set(o, "13865997763");//o.phone="139xxx"
            System.out.println(o);
            Method mname = c.getDeclaredMethod("setName", String.class);
            mname.invoke(o, "小刘");//o.setName
            System.out.println(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //数组的反射
        Object ar = Array.newInstance(double.class, 10);
        //new double[10]
        Array.setDouble(ar, 0, 1.4);
        Array.setDouble(ar, 2, 1.4);
        double ddd = Array.getDouble(ar, 1);
        System.out.println(ddd);
        double[] ar2 = (double[]) ar;
        System.out.println(Arrays.toString(ar2));
    }
}
